package cn.iocoder.yudao.module.trade.config.service;

import cn.iocoder.yudao.framework.business.basic.dao.query.CoreLambdaQueryWrapper;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.datapermission.core.annotation.DataPermission;
import cn.iocoder.yudao.module.trade.config.dal.dataobject.TradeConfigDO;
import cn.iocoder.yudao.module.trade.config.dal.mysql.TradeConfigMapper;
import cn.iocoder.yudao.module.trade.config.vo.TradeConfigSaveReqVO;
import jakarta.annotation.Resource;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.List;

/**
 * 交易中心配置 Service 实现类
 *
 * @author owen
 * @author 山野羡民
 */
@Service
@Validated
public class TradeConfigServiceImpl implements TradeConfigService {
    private static final String TRADE_CONFIG = "xianmin:trade:config";

    @Resource
    private TradeConfigMapper tradeConfigMapper;

    @Override
    @DataPermission(enable = false)
    @CacheEvict(cacheNames = TRADE_CONFIG, key = "#shopId")
    public void saveTradeConfig(Long shopId, TradeConfigSaveReqVO reqVO) {
        TradeConfigDO entity = BeanUtils.toBean(reqVO, TradeConfigDO.class);
        // 存在，则进行更新
        entity.setId(getOrCreateTradeConfigByShopId(shopId).getId());
        entity.setShopId(shopId);
        tradeConfigMapper.updateById(entity);
    }

    @Override
    public TradeConfigDO getTradeConfigById(Long id) {
        return tradeConfigMapper.selectById(id);
    }

    @Override
    @DataPermission(enable = false)
    public TradeConfigDO getOrCreateTradeConfigByShopId(Long shopId) {
        CoreLambdaQueryWrapper<TradeConfigDO> wrapper = new CoreLambdaQueryWrapper<>();
        wrapper.eq(TradeConfigDO::getShopId, shopId);
        wrapper.orderByDesc(TradeConfigDO::getId);
        wrapper.limitN(1);
        TradeConfigDO entity = tradeConfigMapper.selectOne(wrapper);
        if (entity == null) {
            entity = new TradeConfigDO();
            entity.setShopId(shopId);
            entity.setAfterSaleRefundReasons(List.of("质量不好", "与描述不符"));
            entity.setAfterSaleReturnReasons(List.of("不想要了", "拍错"));
            entity.setDeliveryExpressFreeEnabled(true);
            entity.setDeliveryExpressFreePrice(0);
            entity.setDeliveryPickUpEnabled(false);
            tradeConfigMapper.insert(entity);
        }
        return entity;
    }

    @Override
    @Cacheable(cacheNames = TRADE_CONFIG, key = "#shopId", unless = "#result == null")
    public TradeConfigDO getTradeConfigFromCacheByShopId(Long shopId) {
        return getOrCreateTradeConfigByShopId(shopId);
    }

    @Override
    public List<TradeConfigDO> getTradeConfigList() {
        return tradeConfigMapper.selectList();
    }

}
